<template>
  <div id="addPicturePage">
    <h1 class="pageHeader">
      {{ route.query?.id ? '修改图片' : '创建图片' }}
    </h1>
    <a-typography-paragraph v-if="spaceId" type="secondary">
      保存至空间：<a :href="`/space/${spaceId}`" target="_blank">{{ spaceId }}</a>
    </a-typography-paragraph>

    <!-- 图片上传组件 -->
    <a-tabs v-if="!route.query?.id" v-model:activeKey="uploadType">
      <a-tab-pane key="file" tab="文件上传">
        <PictureUpload
          :picture="picture"
          :spaceId="spaceId"
          :user-avatar="false"
          :onSuccess="onSuccess"
        />
      </a-tab-pane>
      <a-tab-pane key="url" tab="URL 上传" force-render>
        <UrlPictureUpload
          :picture="picture"
          :spaceId="spaceId"
          :onSuccess="onSuccess" />
      </a-tab-pane>
    </a-tabs>

    <!-- 文件修改图片展示区域 -->
    <div v-else class="image">
      <img :src="picture?.url" :alt="picture?.name" style="max-width: 100%; max-height: 450px" />
    </div>

    <div v-if="picture" class="edit-bar">
      <a-space size="middle">
        <!-- 修改图片按钮 -->
        <a-button :icon="h(EditOutlined)" @click="doEditPicture">编辑图片</a-button>
        <!-- AI 扩图按钮 -->
        <a-button type="primary" :icon="h(FullscreenOutlined)" @click="doImagePainting" >AI 扩图</a-button>
      </a-space>
      <ImageOutPainting ref="ImageOutPaintingRef" :picture="picture" :space-id="spaceId" :on-success="handleResult" />
      <ImageCropper
        ref="ImageCropperRef"
        :imageUrl="picture.url"
        :picture="picture"
        :spaceId="spaceId"
        :onSuccess="handleResult"
      />
    </div>


    <!-- 图片信息表单 -->
    <a-form
      v-if="picture"
      layout="vertical"
      :model="pictureForm"
      @finish="handleSubmit"
      style="width: 100%"
    >
      <a-form-item name="name" label="图片名称">
        <a-input v-model:value="pictureForm.name" placeholder="输入图片名称" allow-clear />
      </a-form-item>
      <a-form-item name="introduction" label="图片简介">
        <a-textarea
          v-model:value="pictureForm.introduction"
          :auto-size="{ minRows: 2, maxRows: 5 }"
          placeholder="输入图片简介"
          allow-clear
        />
      </a-form-item>

      <a-form-item name="category" label="分类">
        <a-auto-complete
          v-model:value="pictureForm.category"
          placeholder="输入/选择图片分类"
          :options="categoryOptions"
          allow-clear
        />
      </a-form-item>

      <a-form-item name="tags" label="标签">
        <a-select
          v-model:value="pictureForm.tags"
          mode="tags"
          placeholder="输入/选择图片标签"
          :options="tageOptions"
          allow-clear
        />
      </a-form-item>

      <a-form-item>
        <a-button type="primary" html-type="submit" style="width: 100%"
          >{{ route.query?.id ? '保存' : '创建' }}
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import PictureUpload from '@/components/PictureUpload.vue'
import UrlPictureUpload from '@/components/UrlPictureUpload.vue'
import { computed, h, onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import {
  editPictureUsingPost,
  getPictureVoByIdUsingGet,
  listPictureTagCategoryUsingGet,
} from '@/api/pictureController.ts'
import { useRoute, useRouter } from 'vue-router'
import ImageCropper from '@/components/ImageCropper.vue'
import { EditOutlined,FullscreenOutlined } from '@ant-design/icons-vue'
import ImageOutPainting from '@/components/ImageOutPainting.vue'

const picture = ref<API.PictureVO>()
const pictureForm = reactive<API.PictureEditRequest>({})
const uploadType = ref<'file' | 'url'>('file')

// 空间 id (用于私有空间传图)
const spaceId = computed(() => {
  return route.query?.spaceId
})

const onSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
  pictureForm.name = picture.value.name
}

const router = useRouter()

/**
 * 修改图片上传成功后的基本信息
 * @param values
 */
const handleSubmit = async (values: any) => {
  try {
    const pictureId = picture.value?.id
    if (pictureId === null) return

    const res = await editPictureUsingPost({
      id: pictureId,
      spaceId: spaceId.value,
      ...values, // 展开values对象的内容
    })
    // 操作成功跳转到详情页
    if (res.data.code === 0 && res.data.data) {
      if (!picture.value?.spaceId){
        message.success('创建成功，等待管理员审核后可在公共图库查看')
      }else {
        message.success('创建成功')
      }
      // 跳转图片详情页
      await router.push({
        path: `/picture/${pictureId}`,
      })
    } else {
      message.error('创建失败，' + res.data.message)
    }
  } catch (e) {
    message.error('创建失败，' + e)
  }
}

// 定义标签和分类选项变量
const tageOptions = ref<String[]>([])
const categoryOptions = ref<String[]>([])

/**
 * 获取分类和标签选项
 * @param values
 */
const getTagCategoryOptions = async () => {
  try {
    const res = await listPictureTagCategoryUsingGet()
    // 成功
    if (res.data.code === 0 && res.data.data) {
      // 处理获取的数据
      tageOptions.value = (res.data.data.tagList ?? []).map((data: string) => {
        return {
          value: data,
          label: data,
        }
      })
      categoryOptions.value = (res.data.data.categoryList ?? []).map((data: string) => {
        return {
          value: data,
          label: data,
        }
      })
    } else {
      message.error('标签和分类获取失败，' + res.data.message)
    }
  } catch (e) {
    message.error('标签和分类获取失败，' + e)
  }
}

const route = useRoute()

const getOldPicture = async () => {
  // 获取请求参数
  const id = route.query?.id
  // 判断id是否存在
  if (id) {
    // 若id存在，获取图片基本信息
    const res = await getPictureVoByIdUsingGet({ id })
    if (res.data.code === 0 && res.data.data) {
      const data = res.data.data
      picture.value = data
      pictureForm.name = data.name
      pictureForm.introduction = data.introduction
      pictureForm.tags = data.tags
      pictureForm.category = data.category
    }
  }
}


const ImageCropperRef = ref()

// 打开组件框
const doEditPicture = () => {
  if (ImageCropperRef.value){
    ImageCropperRef.value.openModal()
  }
}

// 子组件传来上传处理成功成功的图片
const handleResult = (newPicture: API.PictureVO) => {
  // 将新图片赋值给父组件
  picture.value = newPicture
}

// 打开 AI 扩图框
const ImageOutPaintingRef = ref()

const doImagePainting = () => {
  if (ImageOutPaintingRef.value){
    ImageOutPaintingRef.value.openModal()
  }
}

onMounted(() => {
  getTagCategoryOptions()
  getOldPicture()
})
</script>

<style scoped>
#addPicturePage {
  max-width: 720px;
  margin: 0 auto;
}
#addPicturePage .edit-bar {
  text-align: center;
  margin: 16px 0;
}
#addPicturePage .image {
  max-width: 100%;
  max-height: 480px;
  text-align: center;
  margin-bottom: 20px;
}
</style>
